package com.grade.web.controller.system;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import com.grade.common.core.domain.Ztree;
import com.grade.common.core.domain.entity.SysDept;
import com.grade.common.core.domain.entity.SysDictData;
import com.grade.common.core.domain.entity.SysUser;
import com.grade.common.core.page.DynamicTableDataInfo;
import com.grade.common.utils.ShiroUtils;
import com.grade.system.domain.*;
import com.grade.system.service.IItemGradeRelationService;
import com.grade.system.service.ISysDictDataService;
import com.grade.system.service.ISysDictTypeService;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import com.grade.common.annotation.Log;
import com.grade.common.enums.BusinessType;
import com.grade.system.service.ICreditGradeService;
import com.grade.common.core.controller.BaseController;
import com.grade.common.core.domain.AjaxResult;
import com.grade.common.utils.poi.ExcelUtil;
import com.grade.common.core.page.TableDataInfo;
import org.springframework.web.multipart.MultipartFile;

/**
 * 信用评分Controller
 * 
 * @author grade
 * @date 2021-10-17
 */
@Controller
@RequestMapping("/system/grade")
public class CreditGradeController extends BaseController
{
    private String prefix = "system/grade";

    @Autowired
    private ICreditGradeService creditGradeService;
    @Autowired
    private IItemGradeRelationService itemGradeRelationService;
    @Autowired
    private ISysDictDataService dictDataService;
    @Autowired
    private ISysDictTypeService dictTypeService;

    @RequiresPermissions("system:grade:view")
    @GetMapping()
    public String grade()
    {
        return prefix + "/grade";
    }

    /**
     * 查询信用评分列表
     */
    @RequiresPermissions("system:grade:list")
    @PostMapping("/list")
    @ResponseBody
    public TableDataInfo list(CreditGrade creditGrade)
    {
        startPage();
        List<CreditGrade> list = creditGradeService.selectCreditGradeList(creditGrade);
        return getDataTable(list);
    }

    /**
     * 导出信用评分列表
     */
    @RequiresPermissions("system:grade:export")
    @Log(title = "信用评分", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    @ResponseBody
    public AjaxResult export(CreditGrade creditGrade)
    {
        List<CreditGrade> list = creditGradeService.selectCreditGradeList(creditGrade);
        ExcelUtil<CreditGrade> util = new ExcelUtil<CreditGrade>(CreditGrade.class);
        return util.exportExcel(list, "信用评分数据");
    }

    /**
     * 新增信用评分
     */
    @GetMapping("/add")
    public String add()
    {
        return prefix + "/add";
    }

    /**
     * 新增保存信用评分
     */
    @RequiresPermissions("system:grade:add")
    @Log(title = "信用评分", businessType = BusinessType.INSERT)
    @PostMapping("/add")
    @ResponseBody
    public AjaxResult addSave(CreditGrade creditGrade)
    {
        return toAjax(creditGradeService.insertCreditGrade(creditGrade));

    }

    /**
     * 新增保存信用评分
     */
    @Log(title = "信用评分", businessType = BusinessType.INSERT)
    @GetMapping("/viewGrade/{id}")
    public String viewGrade(@PathVariable("id") Long id, ModelMap mmap)
    {
        CreditGrade creditGrade = creditGradeService.selectCreditGradeById(id);
        String cityLabel = dictDataService.selectDictLabel("b_city",creditGrade.getCity());
        mmap.put("viewTitle", cityLabel+creditGrade.getGradePeriod()+"评分");
        mmap.put("creditGrade", creditGrade);
        mmap.put("viewGradeId", id);
        return prefix + "/viewGrade";
    }

    /**
     * 新增保存信用评分
     */
    @Log(title = "修改信用评分", businessType = BusinessType.INSERT)
    @GetMapping("/editGrade/{id}")
    public String editGrade(@PathVariable("id") Long id, ModelMap mmap)
    {
        CreditGrade creditGrade = creditGradeService.selectCreditGradeById(id);
        String cityLabel = dictDataService.selectDictLabel("b_city",creditGrade.getCity());
        mmap.put("viewTitle", cityLabel+creditGrade.getGradePeriod()+"评分");
        mmap.put("editGradeId", id);
        return prefix + "/editGrade";
    }
    /**
     * 修改保存信用评分
     */
    @RequiresPermissions("system:grade:edit")
    @Log(title = "修改信用评分保存", businessType = BusinessType.UPDATE)
    @PostMapping("/editGrade")
    @ResponseBody
    public AjaxResult editGradeSave(CreditGrade creditGrade)
    {
        return toAjax(creditGradeService.saveEditGrade(creditGrade));
    }

    /**
     * 修改信用评分
     */
    @GetMapping("/edit/{id}")
    public String edit(@PathVariable("id") Long id, ModelMap mmap)
    {
        CreditGrade creditGrade = creditGradeService.selectCreditGradeById(id);
        mmap.put("creditGrade", creditGrade);
        return prefix + "/edit";
    }

    /**
     * 修改保存信用评分
     */
    @RequiresPermissions("system:grade:edit")
    @Log(title = "信用评分", businessType = BusinessType.UPDATE)
    @PostMapping("/edit")
    @ResponseBody
    public AjaxResult editSave(CreditGrade creditGrade)
    {
        return toAjax(creditGradeService.updateCreditGrade(creditGrade));
    }

    /**
     * 删除信用评分
     */
    @RequiresPermissions("system:grade:remove")
    @Log(title = "信用评分", businessType = BusinessType.DELETE)
    @PostMapping( "/remove")
    @ResponseBody
    public AjaxResult remove(String ids)
    {
        return toAjax(creditGradeService.deleteCreditGradeByIds(ids));
    }

    /**
     * 加载部门列表树
     */
    @GetMapping("/treeData")
    @ResponseBody
    public List<Ztree> treeData()
    {
        CreditGrade creditGrade = new CreditGrade();
        List<Ztree> ztrees = creditGradeService.treeData(creditGrade);
        return ztrees;
    }

    @Log(title = "评分模板", businessType = BusinessType.INSERT)
    @PostMapping("/getTemplateById")
    @ResponseBody
    public AjaxResult getTemplateById(CreditGrade creditGrade)
    {
        CreditGrade  grade = creditGradeService.selectCreditGradeById(creditGrade.getId());
        String[]columns = {"firstColumn","secondColumn","threeColumn","fourColumn","fiveColumn","sixColumn"};
        String[]titles = {"一级类型","二级类型","三级类型","四级类型","五级类型","六级类型"};
        List<TableColumn>columnList = new ArrayList<>();
        if(grade!=null){

            for(int i=0;i<grade.getLayer();i++ ){
                TableColumn tableColumn = new TableColumn(titles[i],columns[i]);
                columnList.add(tableColumn);
            }
            TableColumn contentColumn = new TableColumn("评分细则","itemContent");
            TableColumn maxScoreColumn = new TableColumn("封顶分数","maxScore");
            TableColumn weight = new TableColumn("权重(%)","weight");
            TableColumn scoreColumn = new TableColumn("预评分","score");
            TableColumn remarkColumn = new TableColumn("备注","remark");

            columnList.add(contentColumn);
            columnList.add(maxScoreColumn);
            columnList.add(weight);
            columnList.add(scoreColumn);
            columnList.add(remarkColumn);
        }
        return  success(columnList);
    }

    @Log(title = "评分模板", businessType = BusinessType.INSERT)
    @PostMapping("/getGradeItemsByGradeId")
    @ResponseBody
    public TableDataInfo getGradeItemsByGradeId(CreditGrade creditGrade)
    {
        ItemGradeRelation condition = new ItemGradeRelation();
        condition.setGradeId(creditGrade.getId());
        List<ItemGradeRelation> relationList =  itemGradeRelationService.selectItemGradeRelationList(condition);

        //计算可以输入的最高最低分
        if(relationList!=null && relationList.size()>0){
            for(ItemGradeRelation item: relationList){
                Integer maxScore = item.getMaxScore();
                if(maxScore!=null && maxScore>=0){
                    item.setInputMax(maxScore);
                    item.setInputMin(0);
                }else{
                    item.setInputMax(0);
                    item.setInputMin(maxScore);
                }
            }
        }
        return getDataTable(relationList);
    }

    /**
     * 状态修改
     */
    @Log(title = "状态管理", businessType = BusinessType.UPDATE)
    @RequiresPermissions("system:grade:edit")
    @PostMapping("/changeStatus")
    @ResponseBody
    public AjaxResult changeStatus(CreditGrade creditGrade)
    {
        return toAjax(creditGradeService.updateCreditGrade(creditGrade));
    }


    /**
     * 查询信用预评分列表
     */
    @RequiresPermissions("system:gradeQuery:list")
    @PostMapping("/gradeQueryList")
    @ResponseBody
    public TableDataInfo gradeQueryList(CreditGrade creditGrade)
    {
        SysUser currentUser = ShiroUtils.getSysUser();
        String[] citys=new String[]{} ;
        if (currentUser != null&&!currentUser.isAdmin()){
            if(currentUser.getCity()!=null){
                citys = currentUser.getCity().split(",");
            }
            creditGrade.setCitys(citys);
        }

        startPage();
        List<CreditGrade> list = creditGradeService.selectCreditGradeList(creditGrade);
        return getDataTable(list);
    }

    /**
     * 信用大厅-信用预评分查询
     */
    @RequiresPermissions("system:gradeQuery:list")
    @GetMapping("/gradeQuery")
    public String gradeQuery(ModelMap mmap)
    {
        SysUser currentUser = ShiroUtils.getSysUser();
        List<String>citys=new ArrayList<>() ;
        List<SysDictData>cityLabel=new ArrayList<>() ;
        if (currentUser != null&&!currentUser.isAdmin()){
            if(currentUser.getCity()!=null){
                citys = Arrays.asList(currentUser.getCity().split(","));
            }
            if(citys!=null && citys.size()>0){
                List<SysDictData> datas = dictTypeService.selectDictDataByType("b_city");
                //covert value to label

                for(SysDictData data: datas){
                    if(citys.contains(data.getDictValue())){
                        cityLabel.add(data);
                    }
                }
            }
            mmap.put("cityList",cityLabel);
        }else {
            List<SysDictData> datas = dictTypeService.selectDictDataByType("b_city");
            mmap.put("cityList",datas);
        }

        return prefix + "/gradeQuery";
    }


    /**
     * 诊断书管理
     */
    @Log(title = "诊断书管理", businessType = BusinessType.UPDATE)
    @GetMapping("/editDiagnose/{id}")
    public String editDiagnose(@PathVariable("id") Long id, ModelMap mmap)
    {
        CreditGrade creditGrade = creditGradeService.selectCreditGradeById(id);
        String cityLabel = dictDataService.selectDictLabel("b_city",creditGrade.getCity());
        mmap.put("viewTitle", cityLabel+creditGrade.getGradePeriod()+"评分");
        mmap.put("editGradeId", id);
        mmap.put("creditGrade", creditGrade);
        return prefix + "/editDiagnose";
    }

    /**
     * 诊断书编辑
     */
    @RequiresPermissions("system:diagnose:edit")
    @Log(title = "修改诊断书", businessType = BusinessType.UPDATE)
    @PostMapping("/editDiagnose")
    @ResponseBody
    public AjaxResult editDiagnoseSave(CreditGrade creditGrade)
    {
        return toAjax(creditGradeService.saveEditDiagnose(creditGrade));
    }

    /**
     * 获取诊断书
     */
    @Log(title = "诊断书管理", businessType = BusinessType.UPDATE)
    @PostMapping("/getGradeItemsDiagnoseByGradeId")
    @ResponseBody
    public TableDataInfo getGradeItemsDiagnoseByGradeId(CreditGrade creditGrade)
    {
        ItemGradeRelation condition = new ItemGradeRelation();
        condition.setGradeId(creditGrade.getId());
        List<ItemGradeRelation> relationList =  itemGradeRelationService.selectItemGradeRelationDiagnoseList(condition);

        return getDataTable(relationList);
    }

    @Log(title = "诊断书列信息", businessType = BusinessType.INSERT)
    @PostMapping("/getTemplateDiagnoseById")
    @ResponseBody
    public AjaxResult getTemplateDiagnoseById(CreditGrade creditGrade)
    {
        CreditGrade  grade = creditGradeService.selectCreditGradeById(creditGrade.getId());
        String[]columns = {"firstColumn","secondColumn","threeColumn","fourColumn","fiveColumn","sixColumn"};
        String[]titles = {"一级类型","二级类型","三级类型","四级类型","五级类型","六级类型"};
        List<TableColumn>columnList = new ArrayList<>();
        if(grade!=null){

            for(int i=0;i<grade.getLayer();i++ ){
                TableColumn tableColumn = new TableColumn(titles[i],columns[i]);
                columnList.add(tableColumn);
            }
            TableColumn contentColumn = new TableColumn("评分细则","itemContent");
            TableColumn scoreColumn = new TableColumn("预评分","score");
            TableColumn remarkColumn = new TableColumn("备注","remark");
            //TableColumn diagnoseRemarkColumn = new TableColumn("诊断书备注","diagnoseRemark");

            columnList.add(contentColumn);
            columnList.add(scoreColumn);
            columnList.add(remarkColumn);
            //columnList.add(diagnoseRemarkColumn);
        }
        return  success(columnList);
    }
}
